import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../layout/Index.vue'
import Dash from '../views/Dashboard'
import local from '../utils/local'
import SyncRouter from '../router/SyncRouter'
Vue.use(VueRouter)

// 解决重复点击面包屑导航报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Index,
    redirect: '/dashboard',
    children: [
      // 后台首页
      {
        path: '/dashboard',
        meta: { name: '后台首页', icon: 'icon-shouye' },
        component: Dash
      }
    ]
  },
  {
    path: '/login',
    component: () =>
      import(/* webpackChunkName: "login" */ '../views/Login.vue')
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    component: () => import(/* webpackChunkName: "404" */ '../views/Error.vue')
  }
]
// component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
const router = new VueRouter({
  routes
})

calcRoutes()
export function calcRoutes() {
  const role = local.get('role')
  if (!role) return
  // console.log(SyncRouter.routes, role)
  const finallyroute = filterRoute(SyncRouter.routes, role)
  console.log(finallyroute)

  routes[0].children = routes[0].children.concat(finallyroute)
  router.addRoute(routes[0])

  //计算菜单,是计算已经鉴权好的routes[0].children

  const menus = fliterMenus(routes[0].children)
  // console.log(menus)
  local.set('menus', JSON.stringify(menus))
}

//计算菜单的函数
function fliterMenus(arr) {
  return arr.filter(item => {
    //当我们没有hidden的时候,我们就retuen true出去
    if (!item.hidden) {
      //遍历了这个数组的第一层,还要遍历第二层,就用到了递归
      if (item.children) {
        item.children = fliterMenus(item.children)
      }
      return true
    } else {
      return false
    }
  })
}

function filterRoute(arr, r) {
  return arr.filter(item => {
    if (item.meta && item.meta.role) {
      if (item.meta.role.includes(r)) {
        if (item.children) {
          item.children = filterRoute(item.children, r)
        }
        return true
      } else {
        return false
      }
    } else {
      return true
    }
  })
}
//导航守卫 ---路由的钩子
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
